<?php

namespace common\helpers;

use Yii;

/**
 * 自定义实用工具类
 *
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class Debug {

    //调试输出
    public static function dump($data) {
        header('Content-type: text/html; charset=utf-8');
        echo '<pre class="debug">';
        if (is_array($data)) {
            print_r($data);
        } elseif (is_object($data)) {
            var_dump($data);
        } else {
            echo $data;
        }
        echo '</pre>';
    }

    /**
     * 打印SQL语句
     * @param \yii\db\Query $query
     * @return type
     */
    public static function sql($query) {
        $sql = $query->createCommand()->rawSql;
        Yii::error($sql);
        return $sql;
    }

    /**
     * 打印SQL语句
     * @param integer|array $uid
     * @return type
     */
    public static function tester($uid = [], $login = true) {
        $testUsers = ArrayHelper::getValue(Yii::$app->params, 'testUserIds', []);
        if ($login === true) {
            if (Yii::$app->user->isGuest) {
                return false;
            }
            $probeUser = Yii::$app->user->id;
            if (!empty($uid)) {
                if (is_array($uid)) {
                    $testUsers = ArrayHelper::merge($testUsers, $uid);
                } elseif (is_numeric($uid)) {
                    $testUsers[] = $uid;
                }
            }
        } else {
            if (empty($uid)) {
                return false;
            }
            $probeUser = $uid;
            if (is_array($uid)) {
                foreach ($probeUser as $puid) {
                    if (in_array($uid, $testUsers)) {
                        return true;
                    }
                }
                return false;
            }
        }
        return in_array($probeUser, $testUsers);
    }

    /**
     * 打印Request信息
     * @param integer|array $category
     * @return type
     */
    public static function dumpRequest($category = null) {
        if (!$category) {
            $category = __METHOD__;
        }
        $categories = [
            'reports',
            $category
        ];
        $request = Yii::$app->getRequest();
        $headers = $request->getHeaders()->toArray();
        foreach ($headers as $key => $vls) {
            $headers[$key] = $vls[0];
        }
        Yii::info([
            'method' => $request->getMethod(),
            'url' => $request->getUrl(),
            'queryParams' => $request->getQueryParams(),
            'bodyParams' => $request->getBodyParams(),
            'headers' => $headers,
            'userIP' => $request->userIP,
            'serverName' => $request->serverName,
        ], implode("][", $categories));
    }

}
